package com.epfresh.supplier.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.widget.ShareCouponDialog;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.CouponEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyCouponActivity extends BaseActivity implements LoadMoreListView.IXListViewListener {
    private LoadMoreListView mListView;
    private ArrayList<CouponEntity> list;
    Context mContext;
    MinusAdapter adapter;
    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    private int requestSucceedCount = 0;
    private TagPager tagPager = new TagPager();

    View tvInfo, tvHistory, tvShare;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        list = new ArrayList<CouponEntity>();
        mListView.setPullLoadEnable(false); // 设置可滑动
        // mListView.setXListViewListener(this);// 设置滑动监听器
        mContext = this;
        adapter = new MinusAdapter(this, list, R.layout.item_coupon);
        mListView.setAdapter(adapter);
        baseback.setVisibility(View.VISIBLE);
        initHeadView();
        requestOrderList(0);
    }

    void initView() {
        setContentView(R.layout.activity_my_coupon);
        mListView = (LoadMoreListView) findViewById(R.id.listview);
        View footView = View.inflate(this, R.layout.include_footer_coupon, null);//footView
        mListView.addFooterView(footView, null, false);
        tvHistory = findViewById(R.id.tv_history);
        tvInfo = findViewById(R.id.tv_about);
        tvShare = findViewById(R.id.tv_share);
        tvShare.setOnClickListener(this);
        tvInfo.setOnClickListener(this);
        tvHistory.setOnClickListener(this);
        basetitle.setText("优惠券");
/*        rightbtn.setText("帮助");
        rightbtn.setOnClickListener(this);*/
        vException = findViewById(R.id.v_exception);
        mainView = findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
    }


    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }

    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }


    private PtrMdFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return false && PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView() {
        ptrFrameLayout = (PtrMdFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
        hideProgressDialog();
        showMainView();
    }

    boolean refreshFlag = false;

    public void refresh() {
        mListView.resetNoMore();
        refreshFlag = true;
        //requestOrderList(0);
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        // requestOrderList( number + 1);
    }


    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            mListView.noMore();
        } else {
            mListView.stopLoadMore();
        }
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.tv_history:
                Intent coupons = new Intent(this, MyHistoryActivity.class);
                startActivity(coupons);
                break;
            case R.id.tv_about:

                help();
                break;
            case R.id.tv_share:
                if (dialog == null) {
                    toast("请先选择优惠券");
                    return;
                } else {
                    share();
                }
                break;
        }
    }

    private void help() {

        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_SUPPLIER_COUPON);
        intent.putExtra(Constant.KEY_WEB_TITLE, getString(R.string.help));
        startActivity(intent);

    }


    ShareCouponDialog dialog;

    private void share() {
        if (dialog == null)
            dialog = new ShareCouponDialog(this);
     /*   if(flagView!=null){
            dialog.couponId =  (String)flagView.getTag(R.id.item_key_id);
            dialog.couponNumber = (String)flagView.getTag(R.id.item_key_position);
        }*/
        dialog.showDialog(com.epfresh.api.constant.Constant.URL_SHARE_COUPON+"discountId=" + dialog.couponNumber, "http://7xund3.com2.z0.glb.qiniucdn.com/308057047874186068.png?imageView2/2/w/203/h/203", "你在e批生鲜平台还有优惠券没有领，快点来领吧！", "嘿！领优惠券啦！");
    }

    class MinusAdapter extends CommonAdapter<CouponEntity> implements View.OnClickListener {
        Typeface type;

        public MinusAdapter(Context context, ArrayList<CouponEntity> runPacks, int a) {
            super(context, runPacks, a);
            type = Typeface.createFromAsset(mContext.getAssets(), "coupons.ttf");
        }

        int lastRulePosition;
        int lastSelectPosition;

        public void onClick(View v) {
            Object tag = v.getTag(R.id.item_key_position);
            if (tag != null && tag instanceof Integer) {
                int position = (int) tag;
                switch (v.getId()) {
                    case R.id.tv_rule:
                        if (lastRulePosition == position && list.get(lastRulePosition).isInfoFlag() == true) {
                            list.get(lastRulePosition).setInfoFlag(false);
                            notifyDataSetChanged();
                            return;
                        }
                        list.get(lastRulePosition).setInfoFlag(false);
                        list.get(position).setInfoFlag(true);
                        lastRulePosition = position;
                        break;
                    case R.id.rl_main:
                        list.get(lastSelectPosition).setSelect(false);
                        list.get(position).setSelect(true);
                        if (dialog == null)
                            dialog = new ShareCouponDialog((Activity) mContext);
                        dialog.couponId = list.get(position).getId();
                        dialog.couponNumber = list.get(position).getNumber();
                   /*
                       flagView = v;
                       flagView.setTag(R.id.item_key_id, list.get(position).getId());
                       flagView.setTag(R.id.item_key_position,list.get(position).getNumber());
                       */
                        lastSelectPosition = position;
                        break;
                }
                notifyDataSetChanged();
            }
        }

        @Override
        public void convert(final ViewHolder holder, final CouponEntity bean) {
            ((TextView) holder.getView(R.id.tv_money)).setTypeface(type);
            holder.getView(R.id.tv_rule).setTag(R.id.item_key_position, list.indexOf(bean));
            holder.setOnClickListener(R.id.tv_rule, this);
            holder.getView(R.id.rl_main).setTag(R.id.item_key_position, list.indexOf(bean));
            holder.setOnClickListener(R.id.rl_main, this);
            if (bean.isSelect()) {
                holder.getView(R.id.iv_flag).setVisibility(View.VISIBLE);
            } else {
                holder.getView(R.id.iv_flag).setVisibility(View.GONE);
            }
            holder.setText(R.id.tv_number, "剩余" + bean.getUnReceivedAmount() + "张");
            holder.setText(R.id.tv_money, bean.getMinusPrice());
            holder.setText(R.id.tv_hint_main, "满" + bean.getFullPrice() + "元可用");
            holder.setText(R.id.tv_title, bean.getName());
            holder.setText(R.id.tv_time, bean.getBeginTime() + "-" + bean.getEndTime());
            holder.setText(R.id.tv_rule_detail, bean.getDescription());
            if (bean.isInfoFlag()) {
                holder.getView(R.id.tv_rule_detail).setVisibility(View.VISIBLE);
            } else {
                holder.getView(R.id.tv_rule_detail).setVisibility(View.GONE);
            }
        }
    }


    OnRequestListener<List<CouponEntity>> onRequestListener = new OnRequestListener<List<CouponEntity>>() {
        @Override
        public List<CouponEntity> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<CouponEntity>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.order_no, arg + "", HttpRequest.FAIL_DATA_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0) {
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<List<CouponEntity>> response, Object tag) {
            showMainView();
            List<CouponEntity> orderResponse = response.getResponseElement();
            list.addAll(orderResponse);
            adapter.notifyDataSetChanged();
            updateViewStatus(requestTag);
            if (list.size() == 0) {
                //tvShare.setVisibility(View.GONE);
                //showExceptionView(R.mipmap.coupon_no, "还没有优惠券", HttpRequest.FAIL_DATA_EMPTY);
                setContentView(R.layout.activity_no_coupon);
                initNo();
            }else{
                tvShare.setVisibility(View.VISIBLE);
            }

        }
    };

    void initNo(){
        tvHistory = findViewById(R.id.tv_history);
        tvInfo = findViewById(R.id.tv_about);
        tvHistory.setOnClickListener(this);
        tvInfo.setOnClickListener(this);
    }


    private RequestTag requestTag = new RequestTag();

    public void requestOrderList(int page) {

        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        Map<String, String> map = new HashMap<>();
        map.put("isValid", "true");
        entity.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_coupon_coupon_list);
        entity.setParameters(map);
        requestTag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_coupon_coupon_list;
        requestTag.action = page;
        request(entity, requestTag, onRequestListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {

        if (resultCode == RESULT_OK && requestCode == 0x1) {
            Uri uri = data.getData();
            ContentResolver cr = getContentResolver();
            Cursor cursor = cr.query(uri, null, null, null, null);
            try {

                while (cursor.moveToNext()) {
                    // 取得联系人名字
                    int nameFieldColumnIndex = cursor.getColumnIndex(
                            ContactsContract.Contacts.DISPLAY_NAME);

                    String contact = cursor.getString(nameFieldColumnIndex);

                    String ContactId = cursor.getString(cursor
                            .getColumnIndex(ContactsContract.Contacts._ID));

                    Cursor phone = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                    + "=" + ContactId,
                            null, null);
                    String num = "";
                    while (phone.moveToNext()) {
                        num = phone.getString(phone.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));
                        break;//只取第一个,多余一个，弹出个对话框手选？如果返回的number+8613004169999类型的，取后11位？
                    }
                    dialog.setPhone(num);
                    phone.close();
                }

            } finally {

                cursor.close();
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        dialog.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    /*
    *
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Uri contactData = data.getData();
            Cursor cursor = managedQuery(contactData, null, null, null, null);
            cursor.moveToFirst();
            String num = this.getContactPhone(cursor);
        }

    }

    private String getContactPhone(Cursor cursor) {
        int phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
        int phoneNum = cursor.getInt(phoneColumn);
        final List<String> result = new ArrayList<>();
        position = 0;
        if (phoneNum > 0) {
            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);// 获得联系人的ID号
            String contactId = cursor.getString(idColumn);
            // 获得联系人电话的cursor
            Cursor phone = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
            if (phone.moveToFirst()) {
                for (; !phone.isAfterLast(); phone.moveToNext()) {
                    int index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    int typeindex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
                    String phoneNumber = phone.getString(index);
                    result.add(phoneNumber);
                }
                if (!phone.isClosed()) {
                    phone.close();
                }
            }
        }

        if (result.size() > 1) {//如果号码多于2个，则弹出对话框让他选择
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            int size = result.size();
            builder.setTitle("请选择一个号码").setItems(result.toArray(new String[size]), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    position = which;
                }
            }).create().show();
        }

        return result.get(position);
    }

    * */
}
